<template>
  <div class="paper">
    <div class="title">桂林电子科技大学科技园</div>
    <div class="title">入园申请表</div>
    
    <div class="date-info">
      申请时间: {{ formatDate(form.applyDate) }}
    </div>
    
    <div class="subtitle">
      (适用于新成立企业或非独立注册企业)
    </div>
    
    <table>
      <tr>
        <td colspan="7">新设立企业名称: {{ form.itemName }}</td>
      </tr>
      <tr>
        <td>企业法人</td>
        <td>{{ form.contactName }}</td>
        <td>联系电话</td>
        <td>{{ form.contactPhone }}</td>
        <td>邮箱地址</td>
        <td colspan="2">{{ form.contactEmail }}</td>
      </tr>
      <tr>
        <td>经办人</td>
        <td>{{ form.agentName }}</td>
        <td>联系电话</td>
        <td>{{ form.agentPhone }}</td>
        <td>邮箱地址</td>
        <td colspan="2">{{ form.agentEmail }}</td>
      </tr>
      <tr>
        <td>拟注册资本</td>
        <td>{{ form.registerMoney }} 万元</td>
        <td>实际募集资金</td>
        <td>{{ form.raisedMoney }} 万元</td>
        <td>初始员工人数</td>
        <td>{{ form.initialEmployees }}</td>
        <td>预计注册日期</td>
      </tr>
      <tr>
        <td>拟注册企业性质</td>
        <td colspan="6">
          <span v-for="(type, index) in companyTypes" :key="'type-'+index">
            <span class="checkbox" :class="{checked: form.region === type}"></span>{{ type }}
          </span>
        </td>
      </tr>
      <tr>
        <td>所属行业</td>
        <td colspan="3">
          <span v-for="(industry, index) in industries" :key="'industry-'+index">
            <span class="checkbox" :class="{checked: form.industry === industry}"></span>{{ industry }}
          </span>
        </td>
        <td>主营业务</td>
        <td colspan="2">{{ form.mainBusiness }}</td>
      </tr>
      <tr>
        <td>入园业务</td>
        <td colspan="6">
          <span v-for="(business, index) in businesses" :key="'business-'+index">
            <span class="checkbox" :class="{checked: form.businessType.includes(business)}"></span>{{ business }}
          </span>
        </td>
      </tr>
      <tr>
        <td rowspan="3">园区场地租赁需求</td>
        <td>租赁面积</td>
        <td>{{ form.rentalArea }} 平方米</td>
        <td>位置要求</td>
        <td colspan="3">{{ form.locationRequirement }}</td>
      </tr>
      <tr>
        <td>租期</td>
        <td>{{ form.rentalPeriod }} 年</td>
        <td>其他要求</td>
        <td colspan="3">{{ form.otherRequirement }}</td>
      </tr>
    </table>
    
    <table>
      <tr>
        <th colspan="6">股东构成</th>
      </tr>
      <tr>
        <th>股东姓名或名称</th>
        <th>股份比例</th>
        <th>股东性质</th>
        <th>联系电话</th>
        <th>身份证号</th>
        <th>备注</th>
      </tr>
      <tr v-for="(shareholder, index) in form.shareholders" :key="'shareholder-'+index">
        <td>{{ shareholder.name }}</td>
        <td>{{ shareholder.ratio }}%</td>
        <td>{{ shareholder.nature }}</td>
        <td>{{ shareholder.phone }}</td>
        <td>{{ shareholder.idNumber }}</td>
        <td>{{ shareholder.note }}</td>
      </tr>
    </table>
    
    <table>
      <tr>
        <th colspan="8">主要人员简介</th>
      </tr>
      <tr>
        <th>姓名</th>
        <th>出生年月</th>
        <th>职务</th>
        <th>毕业院校</th>
        <th>职称</th>
        <th>学历</th>
        <th>专业</th>
        <th>备注</th>
      </tr>
      <tr v-for="(person, index) in form.members" :key="'person-'+index">
        <td>{{ person.name }}</td>
        <td>{{ person.birthDate }}</td>
        <td>{{ person.job }}</td>
        <td>{{ person.school }}</td>
        <td>{{ person.title }}</td>
        <td>{{ person.education }}</td>
        <td>{{ person.major }}</td>
        <td>{{ person.note }}</td>
      </tr>
    </table>
    
    <table>
      <tr>
        <th colspan="8">入园项目简要介绍和分析</th>
      </tr>
      <tr>
        <td>项目简介</td>
        <td colspan="7">{{ form.projectIntroduction }}</td>
      </tr>
      <tr>
        <td>竞争优势分析</td>
        <td colspan="7">{{ form.competitiveAdvantage }}</td>
      </tr>
      <tr>
        <td>市场前景分析</td>
        <td colspan="7">{{ form.marketProspects }}</td>
      </tr>
      <tr>
        <td>能耗情况</td>
        <td colspan="7">{{ form.energyConsumption }}</td>
      </tr>
      <tr>
        <td>污染情况</td>
        <td colspan="7">{{ form.pollution }}</td>
      </tr>
      <tr>
        <td>噪声情况</td>
        <td colspan="7">{{ form.noise }}</td>
      </tr>
      <tr>
        <td>其他情况</td>
        <td colspan="7">{{ form.otherConditions }}</td>
      </tr>
    </table>
    
    <table>
      <tr>
        <th colspan="8">科技园意见</th>
      </tr>
      <tr>
        <td colspan="8" class="opinion-cell">{{ form.officeOpinion }}</td>
      </tr>
    </table>
    
    <div class="note">
      注:请同时提供法人身份证、知识产权证明材料复印件。教师创办企业请提供教师资格证复印件;
      学生创办企业请提供学生证或毕业证(两年内)复印件。校友企业请提供毕业证或学位证复印件。
    </div>
    
    <div class="no-print">
      <el-button type="primary" @click="printForm">打印申请表</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getEnterpriseApplicationDetail, getImmigrantApplicationDetail } from '@/api/enterpeise'
import type { AjaxResult } from '@/types/resultTypes'

const route = useRoute()
const ruleFormRef = ref<FormInstance>()

// 获取详情
const getDetail = async () => {
  const id = route.query.id
  const type = route.query.type
  
  if (!id) {
    ElMessage.error('缺少必要的参数')
    return
  }

  try {
    const api = type === 'immigrant' ? getImmigrantApplicationDetail : getEnterpriseApplicationDetail
    const response = await api(Number(id))
    const res = response.data as unknown as AjaxResult<ResidencyApplication>
    if (res.code === 200 && res.data) {
      form.value = {
        ...form.value,
        ...res.data
      }
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 初始化时获取数据
onMounted(() => {
  getDetail()
})

// 时间格式化函数
const formatDate = (date: string | Date | null | undefined): string => {
  if (!date) return ''
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

interface EnterpriseMember {
  name: string
  birthDate: string  // YYYY-MM-DD HH:mm:ss
  job: string
  school: string
  title: string
  education: string
  major: string
  note?: string
}

interface Shareholder {
  name: string
  ratio: string
  nature: string
  phone?: string
  idNumber?: string
  note?: string
}

interface ResidencyApplication {
  applyDate: string  // YYYY-MM-DD HH:mm:ss
  itemName: string
  contactName: string
  contactPhone: string
  contactEmail: string
  agentName: string
  agentPhone: string
  agentEmail: string
  registerMoney: number
  raisedMoney: number
  initialEmployees: number
  expectedRegisterDate: string  // YYYY-MM-DD HH:mm:ss
  region: string
  industry: string
  otherIndustry?: string
  mainBusiness: string
  businessType: string[]
  otherBusinessType?: string
  rentalArea: string
  locationRequirement: string
  rentalPeriod: string
  otherRequirement?: string
  shareholders: Shareholder[]
  members: EnterpriseMember[]
  projectIntroduction: string
  competitiveAdvantage: string
  marketProspects: string
  energyConsumption: string
  pollution: string
  noise: string
  otherConditions?: string
  officeOpinion?: string
  remarks?: string
  teacherCertificate?: string
  studentCertificate?: string
  graduationCertificate?: string
}

const form = ref<ResidencyApplication>({
  applyDate: formatDate(new Date()),  // 初始化为当前时间
  itemName: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  agentName: '',
  agentPhone: '',
  agentEmail: '',
  registerMoney: 0,
  raisedMoney: 0,
  initialEmployees: 0,
  expectedRegisterDate: '',
  region: '',
  industry: '',
  mainBusiness: '',
  businessType: [],
  rentalArea: '',
  locationRequirement: '',
  rentalPeriod: '',
  shareholders: [],
  members: [],
  projectIntroduction: '',
  competitiveAdvantage: '',
  marketProspects: '',
  energyConsumption: '',
  pollution: '',
  noise: '',
})

const companyTypes = [
  '大学生创业企业',
  '高校教师创业企业',
  '民营企业',
  '外资企业',
  '股份制企业',
  '国有及国有控股企业',
  '其他企业',
  '校友企业'
]

const industries = [
  '电子信息产业',
  '生物医学产业',
  '新能源产业',
  '新材料产业',
  '先进制造产业',
  '环保节能减排',
  '高技术服务业',
  '软件外包服务业'
]

const businesses = ['研究', '开发', '生产', '销售', '服务']

const printForm = () => {
  window.print()
}

const submitForm = async () => {
  if (!ruleFormRef.value) return
  
  await ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 格式化所有时间字段
        const formData = {
          ...form.value,
          applyDate: dayjs(form.value.applyDate).format('YYYY-MM-DD HH:mm:ss'),
          expectedRegisterDate: dayjs(form.value.expectedRegisterDate).format('YYYY-MM-DD HH:mm:ss'),
          members: form.value.members.map(member => ({
            ...member,
            birthDate: dayjs(member.birthDate).format('YYYY-MM-DD HH:mm:ss')
          }))
        }
        
        // TODO: 调用API提交表单
        console.log('提交的表单数据：', formData)
        ElMessage.success('提交成功')
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      }
    }
  })
}
</script>

<style scoped>
.paper {
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  font-family: SimSun, "宋体", serif;
  font-size: 14px;
  line-height: 1.5;
  color: #000;
}

.title {
  text-align: center;
  font-weight: bold;
  font-size: 18px;
  margin: 20px 0;
}

.subtitle {
  text-align: center;
  font-style: italic;
  margin: 15px 0;
}

.date-info {
  text-align: right;
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin: 10px 0;
}

table, th, td {
  border: 1px solid #000;
}

th, td {
  padding: 5px 8px;
  text-align: left;
  vertical-align: top;
}

.text-center {
  text-align: center;
}

.checkbox {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 1px solid #000;
  margin-right: 5px;
  vertical-align: middle;
}

.checked {
  background-color: #000;
}

.note {
  margin-top: 20px;
  font-size: 12px;
}

.opinion-cell {
  height: 100px;
}

.no-print {
  margin-top: 30px;
  text-align: center;
}

@media print {
  .paper {
    padding: 0;
  }
  .no-print {
    display: none;
  }
}
</style>